<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/3/18 0018
 * Describe: 磨盘回调类
 */

namespace app\index\controller\mopan;

use think\Controller;
use think\Request;
use think\Log;
use app\index\controller\SmsTemplate;
use app\common\controller\system\Docking;
use app\common\controller\chuanglan\ChuanglanSmsApi as CLApi;
use think\Db;

class MoPanCallback extends Controller
{
    public function __construct()
    {
        //日志初始化保存地址
        $requestName = Request::instance()->module();
        $controllerName = Request::instance()->controller();
        $setPath = strtolower("{$requestName}/{$controllerName}/");
        Log::init(['path'=>LOG_PATH.$setPath,'type'  => 'file',]);
    }

    /**
     * 接收磨盘回调数据
     * @param string $tradeNo 订单编号
     * @param string $result 风控结果 APPROVE通过 DENY不通过
     */
    public function getMoPanInfo()
    {
//        $param = '{"tradeNo":"201903130647096545","result":"DENY"}';
        $param = input('post.');
        if(!$param){
            \Think\Log::record('磨盘回调 没有请求数据');
            exit(json_encode(['code' => 203,'msg' => '没有接到请求数据','data' => []],JSON_UNESCAPED_UNICODE));
        }

        //验证磨盘返回状态 APPROVE通过|DENY未通过
        $str = 3;
        $upOrderStatus = '未知';
        switch ($param['result']){
            case 'APPROVE':
                $str = 1;
                $upOrderStatus = '通过';
                break;
            case 'DENY':
                $str = 2;
                $upOrderStatus = '拒绝';
                break;
        }

        // 启动事务
        Db::startTrans();
        try {

            //写入记录表
            $temp = [
                'UserID'      => $this->getUserId($param['tradeNo']), //用户ID
                'OrderSn'     => $param['tradeNo'],                   //订单单号
                'MoPanResult' => $str,                                //磨盘风控出来结果 1通过 2未通过 3未知(原因：磨盘返回结果字段变更)
                'CreateTime'  => date('Y-m-d H:i:s',time()),          //回调时间
                'SourceData'  => json_encode($param),                 //磨盘返回的json源数据
            ];
            $result = db('mopan')->insert($temp);
            if(!$result){
                throw new \Exception('磨盘回调 写入记录表失败 订单单号为 ' . $param['tradeNo']);
            }

            //检测系统是否开启磨盘自动审核订单 开启则订单自动通过 否则无操作
            $isMoPanAuto = db('sys_basicinfo')->find();
            if($isMoPanAuto['fengkong_mopan_kaiguan'] == 1){

                //获取订单信息
                $orderInfo = db('loans_applylist')->where(['OrderSn' => $param['tradeNo']])->find();
                $userInfo = db('mem_info')->where(['ID' => $orderInfo['UserID']])->find();

                //磨盘自动审核订单
                $orderTemp = [
                    'ID'         => $orderInfo['ID'],                    //订单ID
                    'LoanStatus' => ($param['result'] == 'APPROVE')?1:5, //订单状态 待放款 1等待放款 5审核失败
                    'ShTime'     => date('Y-m-d H:i:s',time()),          //审核时间
                    'Status'     => ($param['result'] == 'APPROVE')?2:4, //审核状态 2机审成功 4机审失败
                    'jishen'     => $upOrderStatus,                      //机审结果 磨盘审核结果 “APPROVE”: 通过 “DENY”: 拒绝
                    'FkTime'     => ($param['result'] == 'DENY')?date('Y-m-d H:i:s',time()):'', //机审拒绝的拒绝时间
                    'ShadminID'  => 119,                                 //机审客服ID
                ];
                $upOrderResult = db('loans_applylist')->update($orderTemp);
                if($upOrderResult){

                    //发送审核成功短信通知用户
                    if($param['result'] == 'APPROVE'){
                        $smsTemp = (new SmsTemplate())->getSmsInfo('check_success');
                        $smsTempStr = str_replace('#name#',$userInfo['TrueName'],$smsTemp['Content']);
                        //发送短信
                        $result1 = (new CLApi('notice'))->sendSMS($userInfo['Mobile'],$smsTempStr);
                        $result2 = json_decode($result1,true);
                        if($result2['code'] != 0){
                            \Think\Log::record('磨盘回调 发送成功审核订单短信失败');
                        }
                        //写入对接产品记录表
                        (new Docking())->addDocking(1,($result2['code'] == 0)?2:3,'chuanglan','磨盘回调 - 机审订单审核成功短信通知',$result1);
                    }

                    //发送审核失败的短信通知
                    if($param['result'] == 'DENY'){
                        $smsTemp = (new SmsTemplate())->getSmsInfo('check_failed');
                        $smsTempStr = str_replace('#name#',$userInfo['TrueName'],$smsTemp['Content']);
                        //发送短信
                        $result3 = (new CLApi('notice'))->sendSMS($userInfo['Mobile'],$smsTempStr);
                        $result4 = json_decode($result3,true);
                        if($result4['code'] != 0){
                            \Think\Log::record('磨盘回调 发送审核失败短信失败');
                        }

                        //写入对接产品记录表
                        (new Docking())->addDocking(1,($result4['code'] == 0)?2:3,'chuanglan','磨盘回调 - 机审订单审核失败短信通知',$result3);
                    }
                }else{
                    throw new \Exception('磨盘回调 订单自动审核操作失败 订单单号为' . $param['tradeNo']);
                }
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            //写入错误日志
            \Think\Log::record($e->getMessage());
            exit(json_encode(['code' => 204,'msg' => '处理失败','data' => []],JSON_UNESCAPED_UNICODE));
        }

        exit(json_encode(['code' => 0,'msg' => '请求成功','data' => []],JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取用户ID
     * @return string $orderSn 订单编号
     * @return int
     */
    public function getUserId($orderSn)
    {
        return db('loans_applylist')->where(['OrderSn' => $orderSn])->value('UserID');
    }


}